<template>
  <component v-if="buttonList.length > 0" :is="props.render ? props.render(renderDom, data, buttonList) : renderDom" />
</template>

<script setup>
import { h, computed } from 'vue';
import RenderButtons from './render-buttons.vue';
import { handleButtonConfig } from './utils';

const props = defineProps({
  access: [String, Object],
  type: {
    type: String,
    default: 'button',
  },
  space: String,
  inline: Boolean,
  wrap: Boolean,
  reverse: Boolean,
  layout: String,
  data: Object,
  buttons: {
    type: Array,
    default: () => [],
  },
  baseProps: Object,
  sortRenderKeys: [Array, Object],
  render: Function,
  eventMap: Object,
  style: Object,
});

const buttonList = computed(() => {
  const sortIndex = props.buttons
    .map((item, index) => {
      let sort = index;
      if (item.sort !== void 0) sort = item.sort;
      if (Array.isArray(props.sortRenderKeys)) {
        sort = props.sortRenderKeys.indexOf(item.key);
      } else if (props.sortRenderKeys?.[item.key] !== void 0) {
        sort = props.sortRenderKeys[item.key];
      }
      return sort !== void 0 ? { index, sort } : null;
    })
    .filter(Boolean);

  sortIndex.sort((x, y) => x.sort - y.sort);
  console.log(sortIndex);

  const sortedButtons = sortIndex.map((item) => props.buttons[item.index]);
  return handleButtonConfig(sortedButtons, props.data, props.type);
});

const renderDom = h(RenderButtons, {
  blockName: typeof props.access === 'object' ? props.access.name : props.access || '',
  type: props.type,
  space: props.space,
  inline: props.inline,
  wrap: props.wrap,
  reverse: props.reverse,
  layout: props.layout,
  buttons: buttonList.value,
  baseProps: props.baseProps,
  eventData: props.data,
  eventMap: props.eventMap || {},
  style: props.style,
});
</script>
